package com.atmilan.quartz.utils.product;

import com.alibaba.fastjson.JSONObject;
import com.atmilan.quartz.config.RestTemplateConfig;
import com.atmilan.quartz.model.dto.paolo.PaoloProductResDTO;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.JsonObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

/**
 * 功能描述: 拉取商品源数据
 *
 * @Author: wangzh
 * @Date: 2023/2/8 17:27
 */
@Slf4j
@Service
public class PaoloProductUtil {

    @Autowired
    private RestTemplateConfig restTemplateConfig;

    @Value("${paolo.url}")
    private String paoloUrl;
    @Value("${paolo.client}")
    private String paoloClient;
    @Value("${paolo.token}")
    private String paoloToken;
    @Value("${paolo.channelKey}")
    private String paoloChannelKey;

    /**
     * 功能描述: 获取Paolo供应商商品数据
     * @Param: []
     * @Return: com.atmilan.quartz.model.dto.paolo.PaoloProductResDTO
     * @Author: wangzh
     * @Date: 2023/2/13 14:25
     */
    public PaoloProductResDTO selectPaolo() {
        PaoloProductResDTO paoloProductResDTO = null;
        try {
            StringBuilder stringBuilder = new StringBuilder();
            stringBuilder.append(paoloUrl)
                    .append(paoloClient)
                    .append("/products?channelKey=")
                    .append(paoloChannelKey);
            RestTemplate restTemplate = restTemplateConfig.restTemplate();
            // 设置请求头
            HttpHeaders httpHeaders = new HttpHeaders();
            httpHeaders.add("Cache-Control", "no-cache");
            httpHeaders.add("Ocp-Apim-Subscription-Key", "44f31b29c72a4de1b685153a7db44f9e");
            HttpEntity<Object> formEntity = new HttpEntity<>(httpHeaders);
            // 发送请求
            ResponseEntity<String> response = restTemplate.exchange(stringBuilder.toString(), HttpMethod.GET, formEntity, String.class);
            if (HttpStatus.OK != response.getStatusCode()) {
                JSONObject message = JSONObject.parseObject(response.getBody());
                String errorMessage = message.getString("message");

                log.info("--------------- paolo获取产品列表异常{} ---------------", errorMessage);
            }
            ObjectMapper mapper = new ObjectMapper();
            paoloProductResDTO = mapper.readValue(response.getBody(), PaoloProductResDTO.class);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return paoloProductResDTO;
    }
}
